package com.mxpio.erp.quality.service.impl;

import com.mxpio.erp.common.quality.entity.VEInspectionBillAssembleBadBack;
import com.mxpio.erp.common.quality.entity.VEInspectionBillInspectionTasks;
import com.mxpio.erp.common.quality.entity.VEInspectionBillUnqualifiedParts;
import com.mxpio.erp.common.quality.service.VEInspectionBillAssembleBadBackService;
import com.mxpio.erp.common.quality.service.VEInspectionBillInspectionTasksService;
import com.mxpioframework.common.vo.Result;
import com.mxpioframework.excel.importer.model.Entry;
import com.mxpioframework.jpa.JpaUtil;
import com.mxpioframework.jpa.lin.Linq;
import com.mxpioframework.jpa.query.Criteria;
import com.mxpioframework.jpa.query.Operator;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service
public class VEInspectionBillAssembleBadBackServiceImpl implements VEInspectionBillAssembleBadBackService {
    @Override
    @Transactional
    public List<VEInspectionBillAssembleBadBack> list(Criteria c) {
        return JpaUtil.linq(VEInspectionBillAssembleBadBack.class).where(c).list();
    }

    @Override
    @Transactional
    public Page<VEInspectionBillAssembleBadBack> listPage(Pageable pageAble) {
        List<VEInspectionBillAssembleBadBack> veInspectionBillAssembleBadBacks  = new ArrayList<>();

        //存储拆分后的数据
        ArrayList<VEInspectionBillAssembleBadBack> newList = new ArrayList<>();

        LocalDate today = LocalDate.now(); // 获取当前日期
        String year =Integer.toString(today.getYear()); // 获取年份
//        Criteria c = Criteria.create().addCriterion("year", Operator.EQ, year);
//        c.addCriterion("year", Operator.EQ, year);

        Linq linq =JpaUtil.linq(VEInspectionBillAssembleBadBack.class);
        List<VEInspectionBillAssembleBadBack> list = linq.equal("year", year).list();
        //查询到当年的所有数据
//        List<VEInspectionBillAssembleBadBack> list = linq.aliasToBean(VEInspectionBillAssembleBadBack.class).select("year", "yearMonth", "exceptionType",
//                 linq.criteriaBuilder().sum(linq.root().get("exceptionQuantity")).alias("exceptionQuantity"))
//                .where(c)
//                .groupBy("year", "yearMonth", "exceptionType")
//                .list();
        //拆分多类型
        for (VEInspectionBillAssembleBadBack vEInspectionBillAssembleBadBack : list){
            if (vEInspectionBillAssembleBadBack.getExceptionType() !=null){
                String exceptionType = vEInspectionBillAssembleBadBack.getExceptionType();
                String[] types = exceptionType.split(",");//拆分多类型
                if (types.length > 1) {
                    for (String type : types) {
                        VEInspectionBillAssembleBadBack badBack = new VEInspectionBillAssembleBadBack();
                        badBack.setYear(vEInspectionBillAssembleBadBack.getYear());
                        badBack.setYearMonth(vEInspectionBillAssembleBadBack.getYearMonth());
                        badBack.setExceptionType(type);
                        badBack.setExceptionQuantity(vEInspectionBillAssembleBadBack.getExceptionQuantity());
                        newList.add(badBack);
                    }
//                //移出原始的数据
//                list.remove(vEInspectionBillAssembleBadBack);
                }else {
                    newList.add(vEInspectionBillAssembleBadBack);
                }
            }
        }
        //得到去重后的所有类型
        Set<String> seenTypes = new HashSet<>();
        List<VEInspectionBillAssembleBadBack> uniqueList = new ArrayList<>();
        for (VEInspectionBillAssembleBadBack item : newList) {
            if (seenTypes.add(item.getExceptionType())) {
                uniqueList.add(item);
            }
        }
            BigDecimal totalYear = BigDecimal.ZERO;
        //取全年的不合格数量
        for (VEInspectionBillAssembleBadBack vEInspectionBillAssembleBadBack : newList){
            totalYear = totalYear.add(vEInspectionBillAssembleBadBack.getExceptionQuantity());
        }
        //计算各个类型当年的不合格数量
            for (VEInspectionBillAssembleBadBack vEInspectionBillAssembleBadBack : uniqueList){
                VEInspectionBillAssembleBadBack badBack = new VEInspectionBillAssembleBadBack();
                badBack.setExceptionType(vEInspectionBillAssembleBadBack.getExceptionType());//类型
                BigDecimal typeTotalYear = BigDecimal.ZERO;
                for (VEInspectionBillAssembleBadBack vEInspectionBillAssembleBadBack1 : newList){
                    if (StringUtils.equals(badBack.getExceptionType(),vEInspectionBillAssembleBadBack1.getExceptionType())){
                        typeTotalYear = typeTotalYear.add(vEInspectionBillAssembleBadBack1.getExceptionQuantity());
                    }
                }
                badBack.setLastYear(typeTotalYear.divide(totalYear, 2, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)));//全年累计占比

                //计算上个月的占比
                //上月总数量
                LocalDate lastMonth = today.minusMonths(1);
                // 格式化日期为 "yyyy-MM" 格式
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");
                String formattedLastMonth = lastMonth.format(formatter);
                //上个月所有类型不合格数量
                BigDecimal lastMonthNum= BigDecimal.ZERO;
                BigDecimal lastMonthNumType= BigDecimal.ZERO;
                for (VEInspectionBillAssembleBadBack vEInspectionBillAssembleBadBack1 : newList){
                    if (StringUtils.equals(formattedLastMonth,vEInspectionBillAssembleBadBack1.getYearMonth())){
                        lastMonthNum = lastMonthNum.add(vEInspectionBillAssembleBadBack1.getExceptionQuantity());
                        //上个月类型的补一个占比
                        if (StringUtils.equals(badBack.getExceptionType(),vEInspectionBillAssembleBadBack1.getExceptionType())){
                            lastMonthNumType = lastMonthNumType.add(vEInspectionBillAssembleBadBack1.getExceptionQuantity());
                        }
                    }
                }
                if (lastMonthNum.compareTo(BigDecimal.ZERO) > 0) {
                    badBack.setLastMonth(lastMonthNumType.divide(lastMonthNum, 2, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)));
                }else {
                    badBack.setLastMonth(BigDecimal.ZERO);
                }
                //上月累计占比
                veInspectionBillAssembleBadBacks.add(badBack);

//                //将当月的数量存在
//
//                for (VEInspectionBillAssembleBadBack vEInspectionBillAssembleBadBack1 : newList){
//
//                }
            }
            return new PageImpl<>(veInspectionBillAssembleBadBacks, pageAble, veInspectionBillAssembleBadBacks.size());
        }


    @Override
    @Transactional
    public Result<?> getlist(Criteria criteria) {
        ArrayList<VEInspectionBillAssembleBadBack> newList  = new ArrayList<>();

        // 获取当前日期
        LocalDate today = LocalDate.now();

        // 创建一个DateTimeFormatter来格式化日期为YYYY-MM格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");

        // 使用formatter格式化today日期
        String formattedDate = today.format(formatter);
//        criteria.addCriterion("yearMonth ",Operator.EQ, formattedDate);
        Linq linq =JpaUtil.linq(VEInspectionBillAssembleBadBack.class);
        List<VEInspectionBillAssembleBadBack> list = linq.equal("yearMonth", formattedDate).list();
//        List<VEInspectionBillAssembleBadBack> list = linq.aliasToBean(VEInspectionBillAssembleBadBack.class).select("yearMonth", "exceptionType",
//                        linq.criteriaBuilder().sum(linq.root().get("exceptionQuantity")).alias("exceptionQuantity"))
//                .where(criteria)
//                .groupBy("yearMonth", "exceptionType")
//                .list();
        for (VEInspectionBillAssembleBadBack vEInspectionBillAssembleBadBack : list) {
            if (vEInspectionBillAssembleBadBack.getExceptionType() != null){
                String exceptionType = vEInspectionBillAssembleBadBack.getExceptionType();
                String[] types = exceptionType.split(",");//拆分多类型
                if (types.length > 1) {
                    for (String type : types) {
//                    for (VEInspectionBillAssembleBadBack badBack : list){
//                        //将多类型的字符添加到各自对应的数据中
//                        if (badBack.getExceptionType().equals(type)){
//                            badBack.setExceptionQuantity(badBack.getExceptionQuantity().add(vEInspectionBillAssembleBadBack.getExceptionQuantity()));
//                        }
//                    }
                        VEInspectionBillAssembleBadBack badBack = new VEInspectionBillAssembleBadBack();
                        badBack.setYear(vEInspectionBillAssembleBadBack.getYear());
                        badBack.setYearMonth(vEInspectionBillAssembleBadBack.getYearMonth());
                        badBack.setExceptionType(type);
                        badBack.setExceptionQuantity(vEInspectionBillAssembleBadBack.getExceptionQuantity());
                        newList.add(badBack);
                    }
                }else {
                    newList.add(vEInspectionBillAssembleBadBack);
                }
            }
        }
        Map<String, BigDecimal> exceptionTypeMap = new HashMap<>();

        // 遍历列表，累加exceptionQuantity
        for (VEInspectionBillAssembleBadBack item : newList) {
            exceptionTypeMap.merge(item.getExceptionType(), item.getExceptionQuantity(), BigDecimal::add);
        }

        // 将结果放入新的List中，这里使用Map作为列表的元素以存储结果
        List<Map<String, Object>> resultList = new ArrayList<>();
        for (Map.Entry<String, BigDecimal> entry : exceptionTypeMap.entrySet()) {
            Map<String, Object> resultEntry = new HashMap<>();
            resultEntry.put("exceptionType", entry.getKey());
            resultEntry.put("exceptionQuantity", entry.getValue());
            resultList.add(resultEntry);
        }
        List<VEInspectionBillAssembleBadBack> veInspectionBillAssembleBadBacks = new ArrayList<>();
        for (Map<String, Object> resultEntry : resultList) {
            VEInspectionBillAssembleBadBack badBack = new VEInspectionBillAssembleBadBack();
            badBack.setExceptionType(resultEntry.get("exceptionType").toString());
            badBack.setExceptionQuantity(new BigDecimal(resultEntry.get("exceptionQuantity").toString()));
            veInspectionBillAssembleBadBacks.add(badBack);
        }



        return Result.OK(veInspectionBillAssembleBadBacks);


    }
}
